package game.ioc;

import game.util.cache.CacheList;
import game.util.parse.ParseConfigFiles;

import java.util.HashMap;

import org.apache.log4j.Logger;


/**
 * get ioc class
 * 
 * @author david
 * 
 */
public class ProductInstance {
	private static final Logger logger = Logger.getLogger(ProductInstance.class);

	public synchronized static Object getInstance(String key) {
		int x = key.lastIndexOf(" ");
		key = key.substring(x + 1, key.length());
		return getIocInstance(key);
	}
	
	@SuppressWarnings("unchecked")
	public synchronized static Object getIocInstance(Object key) {
		Object obj = null;
		try {
			if (CacheList.XmlIoc == null)
				CacheList.XmlIoc = new HashMap();
			
			if (CacheList.XmlIoc.size() <= 0)
				ParseConfigFiles.getIOCCache();
			
			String url = (String) CacheList.XmlIoc.get(key);
			obj = getInstanceByPath(url);
		} catch (Exception e) {
			logger.info("ProductInstance.getIocInstance() - key: " + key);
			logger.error(e.toString());
		}
		return obj;
	}
	
	@SuppressWarnings("unchecked")
	public synchronized static Object getPageInstance(Object key) {
		Object obj = null;
		try {
			if (CacheList.XmlPage == null)
				CacheList.XmlPage = new HashMap();
			
			if (CacheList.XmlPage.size() <= 0)
				ParseConfigFiles.getPageCache();

			String url = (String) CacheList.XmlPage.get(key);
			obj = getInstanceByPath(url);
		} catch (Exception e) {
			logger.info("ProductInstance.getPageInstance(): key: "+ key);
//			e.printStackTrace();
			logger.error(e.toString());
		}
		return obj;
	}
	
	/**
	 * get instance
	 * 
	 * @param url
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private static Object getInstanceByPath(String url) {
		Object ci = null;
		try {
			Class cl = Class.forName(url);
			if(cl == null)
				return null;
			ci = (Object) cl.newInstance();
		} catch (Exception e) {
			logger.info("ProductInstance.getInstanceByPath() - url: " + url);
			e.printStackTrace();
		}
		return ci;
	}

	/**
	 * Get the remote service instance.
	 * 
	 * @param key String;
	 * @return
	 */
	public static Object getRServiceInstance(String key) {
		Object obj = null;
		try {
			if (CacheList.xmlRService == null)
				CacheList.xmlRService = new HashMap<String, String>();
			
			if (CacheList.xmlRService.size() <= 0)
				ParseConfigFiles.loadRServiceConf();
			
			String url = CacheList.xmlRService.get(key);
			obj = getInstanceByPath(url);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("ProductInstance======getRServiceInstance======"+e.toString());
			logger.error(e.toString());
		}
		return obj;
	} // getRServiceInstance()
	
}
